package com.hu.chat.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述：
 *
 * @Author huyouzhong
 * @Date 2024/1/3 10:29
 */
@Component
public class WebInterceptor implements HandlerInterceptor {

    private final static ThreadLocal<Integer> userId = new ThreadLocal<>();

    public static Integer getUserId() {
        return userId.get();
    }

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader("token");
        }
        if (token != null) {
            userId.set(Integer.valueOf(token));
            return true;
        }
        response.sendRedirect("login.html");
        return false;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {
        userId.remove();
    }

}
